/*
 *  cop.cpp
 *  
 *
 *  Created by Brian Bilbo on 12/03/09.
 *
 */

#include "cop.h"
#include "map.h"
#include "robber.h"
#include <iostream>
#include <math.h>

Cop::Cop(Position *_myPosition, Map* _map) {
	catchRadius = 5;
	sightRadius = 10;
	myPosition = _myPosition;
	myInitialPosition = new Position(_myPosition->posX, _myPosition->posY);
	lastKnownRobberPosition = new Position();
	map = _map;
	goToCenter = true;
}

Cop::~Cop() {
	delete myPosition;
	delete lastKnownRobberPosition;
}

Position* Cop::traceRobber()
{
 Position* res =  new Position();
 
 for (int i = 0; i < other_cops.size(); i++){
	if (lastKnownRobberPosition != NULL)
		res = lastKnownRobberPosition;
 }
	
 return res;
}

void Cop::takeTurn() {	
	int tempX = 0;
	int tempY = 0;
	//(map->nodes[myPosition->posX][myPosition->posY])->copsFlag = false;
	if (withinRadius(robber->myPosition, myPosition, sightRadius)) {
		// tell other cops where robber is
		for (int j = 0; j < other_cops.size(); j++){
			other_cops[j]->lastKnownRobberPosition = robber->myPosition;
			other_cops[j]->lastKnownRobberDirection = robber->myDirection;
		}
		driveTo(robber->myPosition);
	} else {
		//driveTo(traceRobber());
		
		if (goToCenter) {
			driveTo(50, 50);
		} else {
			driveTo(myInitialPosition);
		}
		if (myPosition->posX == 50 && myPosition->posY == 50) {
			goToCenter = false;
		} else if (myInitialPosition->posX == myPosition->posX && myInitialPosition->posY == myPosition->posY) {
			goToCenter = true;
		}
		
	}
	
	if (myPosition->posX % 10 != 0)
		tempX = (int) ceil((myPosition->posX)/10);
	else
		tempX = myPosition->posX/10;
	if (myPosition->posY % 10 != 0)
		tempY = (int) ceil((myPosition->posY)/10);
	else
		tempY = myPosition->posY/10;
	
	(map->nodes[tempX][tempY])->copsFlag = true;
}

void Cop::addRobber(Robber *_robber) {
	robber = _robber;
}

void Cop::addCops(std::vector<Cop*> cops) {
	for (int ii = 0; ii < cops.size(); ii++) {
		if (cops[ii] != this) {
			other_cops.push_back(cops[ii]);
		}
	}
}

void Cop::robberWhereabouts(Position *robberPosition, Direction robberDirection) {
	lastKnownRobberPosition->posX = robberPosition->posX;
	lastKnownRobberPosition->posY = robberPosition->posY;
	lastKnownRobberDirection = robberDirection;
}